﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc.Ajax;
using System.Web.Mvc;
using System.Text;

namespace ATest.Helpers
{
    public static class AjaxHelpers
    {
        public static string DeleteLink(this AjaxHelper ajax, string confirmMessage, object routeValues, string updateTargetId)
        {
            //geturl to submit to
            var urlHelper = new UrlHelper(ajax.ViewContext.RequestContext);
            var url = urlHelper.Action("Delete", ajax.ViewContext.RouteData.GetRequiredString("controller"), routeValues);
            //get html helper fo anti forgery token
            var html = new HtmlHelper(ajax.ViewContext, ajax.ViewDataContainer);

            var sb = new StringBuilder();
            sb.AppendFormat(@"<form class=""delete-link"" onsubmit=""Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), {{ insertionMode: Sys.Mvc.InsertionMode.replace, confirm: '{0}', httpMethod: 'Post', updateTargetId: '{1}', onBegin: Function.createDelegate(this, ajaxBegin), onFailure: Function.createDelegate(this, ajaxFailure), onSuccess: Function.createDelegate(this, ajaxSuccess) }});"" method=""post"" action=""{2}"">", confirmMessage, updateTargetId, url);
            sb.Append(html.AntiForgeryToken());
            sb.Append("<input type=\"submit\" value=\"Delete\"/>");
            sb.Append("</form>");
            sb.AppendFormat("<a class=\"delete-link\" href=\"{0}\">Delete</a>", url);

            return sb.ToString();
        }

        public static AjaxOptions DefaultAjaxOptions(this AjaxHelper ajax, string updateTargetId)
        {
            return ajax.DefaultAjaxOptions(updateTargetId, "GET", InsertionMode.Replace, null);
        }
        
        public static AjaxOptions DefaultAjaxOptions(this AjaxHelper ajax, string updateTargetId, string httpMethod)
        {
            return ajax.DefaultAjaxOptions(updateTargetId, httpMethod, InsertionMode.Replace, null);
        }
        public static AjaxOptions DefaultAjaxOptions(this AjaxHelper ajax, string updateTargetId, string httpMethod, InsertionMode insertionMode, string confirm)
        {
            var tmp = new AjaxOptions();
            if(!String.IsNullOrEmpty(confirm))
            {
                tmp.Confirm = confirm;
            }
            tmp.HttpMethod = httpMethod;
            tmp.InsertionMode = insertionMode;
            tmp.UpdateTargetId = updateTargetId;
            tmp.OnBegin = "ajaxBegin";
            tmp.OnFailure = "ajaxFailure";
            tmp.OnSuccess = "ajaxSuccess";
            return tmp;
        }
    }
}
